/*** In The Name of Allah ***/
package com.codeanalysissys.backend.python;
//
import com.codeanalysissys.backend.cpp.CppDDGBuilder;
import com.codeanalysissys.backend.graphs.pdg.ControlDependenceGraph;
import com.codeanalysissys.backend.graphs.pdg.DataDependenceGraph;
import com.codeanalysissys.backend.graphs.pdg.ProgramDependeceGraph;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Program Dependence Graph (PDG) builder for Python programs.
 * A Java parser generated via ANTLRv4 is used for this purpose.
 * This implementation is based on ANTLRv4's Visitor pattern.
 *
 * @author Seyed Mohammad Ghaffarian
 */
public class PythonPDGBuilder {

	/**
	 * Builds and returns Program Dependence Graphs (PDG) for each given Python file.
	 */
	public static ProgramDependeceGraph[] buildForAll(String[] pythonFilePaths) throws IOException {
		File[] pythonFiles = new File[pythonFilePaths.length];
		for (int i = 0; i < pythonFiles.length; ++i)
			pythonFiles[i] = new File(pythonFilePaths[i]);
		return buildForAll(pythonFiles);
	}

	/**
	 * Builds and returns Program Dependence Graphs (PDG) for each given Pythoan file.
	 */
	public static ProgramDependeceGraph[] buildForAll(File[] pythonFiles) throws IOException {

		ControlDependenceGraph[] ctrlSubgraphs;
		ctrlSubgraphs = new ControlDependenceGraph[pythonFiles.length];
		//构建CDG子图
		for (int i = 0; i < pythonFiles.length; ++i)
			ctrlSubgraphs[i] = PythonCDGBuilder.build(pythonFiles[i]);
        //构建DDG子图
		DataDependenceGraph[] dataSubgraphs;
		dataSubgraphs = PythonDDGBuilder.buildForAll(pythonFiles);
		//
		// Join the subgraphs into PDGs
		ProgramDependeceGraph[] pdgArray = new ProgramDependeceGraph[pythonFiles.length];
		for (int i = 0; i < pythonFiles.length; ++i) {
			pdgArray[i] = new ProgramDependeceGraph(pythonFiles[i].getName(),
					ctrlSubgraphs[i], dataSubgraphs[i]);
		}
		return pdgArray;
	}

	public static ProgramDependeceGraph build(InputStream content) throws IOException {
		return new ProgramDependeceGraph(PythonCDGBuilder.build(content), PythonDDGBuilder.build(content));
	}
}

